<template>
  <div>
    <a-upload
        v-model:file-list="fileList"
        name="file"
        list-type="picture-card"
        :data="{path:path}"
        :headers="headers"
        class="avatar-uploader"
        :show-upload-list="true"
        :action="getBaseURL()+'/minio/upload'"
        :before-upload="beforeUpload"
        @change="handleChange"
    >
      <div>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">选择图片</div>
      </div>
    </a-upload>
  </div>
</template>
<script setup>
import {getBaseURL} from "@/config/common.js";
const userStore = useStore.userState()
const loading = ref(false);
const props = defineProps({
  "modelValue":{
    type:String,
    default:""
  },
  path:{
    type:String,
    path:"default"
  }
})
// 自定义事件，用于图片上传成功，把上传的图片推送到状态modelValue中
const emits = defineEmits(["update:modelValue"])
// 回填组件渲染图片
const fileList = ref([{
  uid:getUUID(),
  name:getUUID(),
  status:"done",
  url: props.modelValue
}]);
const headers = ref({})

/*
* 上传执行成功回调的地方。
* 你文件信息就会包括一个：response对象
* 这个对象就有你服务器返回的信息
* */

const handleChange = (info) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') { // 上传成功执行的地方
    loading.value = false;
    fileList.value = [{
      uid:info.file.uid,
      name:info.file.name,
      status:info.file.status,
      url: info.file.response.data
    }]
    emits("update:modelValue",info.file.response.data)
  }

  if (info.file.status === 'error') {
    loading.value = false;
    message.error('上传失败了.....');
  }
};

/**
 * 用于验证文件信息或者大小控制判断
 * @param file
 */
const beforeUpload = (file) => {
  const token = userStore.token
  headers.value = {"token":token}
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('请选择一个图片进行操作!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('你上传的图片文件不能超过2MB!');
  }
  return isJpgOrPng && isLt2M;
};

</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
